package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.RegionPoMapper;
import com.woniu.outlet.po.RegionPo;
import com.woniu.outlet.rabbitmq.MessageRepo;
import com.woniu.outlet.redis.RedisRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class RegionAdapter {

    @Autowired
    private RegionPoMapper regionPoMapper;

    @Autowired
    private RedisRepo redisRepo;

    @Autowired
    private MessageRepo messageRepo;


    public List<RegionPo> findRegions() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("region:list");
        List<RegionPo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List<RegionPo>>() {
            });
            return lists;
        }
        lists = regionPoMapper.selectByExample(null);
        //存到redis
        redisRepo.saveRedisRepo("region:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public RegionPo getRegionById(Long id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("region:" + id);
        RegionPo regionPo = null;
        if (!StringUtils.isEmpty(str)) {
            regionPo = mapper.readValue(str, new TypeReference<RegionPo>() {
            });
            return regionPo;
        }
        regionPo = regionPoMapper.selectByPrimaryKey(id);
        //存到redis
        redisRepo.saveRedisRepo("region:"+id,mapper.writeValueAsString(regionPo));
        return regionPo;
    }

    public void addRegion(RegionPo regionPo){
        regionPoMapper.insert(regionPo);
        redisRepo.deleteRedisRepo("region:list");

    }

    public void updateRegion(RegionPo regionPo){
        regionPoMapper.updateByPrimaryKeySelective(regionPo);
        redisRepo.deleteRedisRepo("region:list");
    }

    public void deleteRegionById(Long id){
        regionPoMapper.deleteByPrimaryKey(id);
        redisRepo.deleteRedisRepo("region:list");
    }
}
